from wxpyview.ui.component.common.basewidget import *

class TreeCtrl(Widget):
    def _getParentParam(self, meta_widget):
        stopping_point = ['Panel', 'Frame']       
        return ComponentLibrary.findFirstMatchedAncestor(meta_widget, stopping_point)
    
    def _setParams(self, meta_widget):
        dom = meta_widget.getDOM()
        if not dom:
            raise IOException
        
        self.params["parent"] = self._getParentParam(meta_widget)
        self.params["id"] = -1
        self.params["pos"] = ComponentLibrary.getPosParam(dom)
        self.params["size"] = ComponentLibrary.getSizeParam(dom)      
        #self.params["style"]
        #self.params["validator"]
        self.params["name"] = dom.getAttribute("name")
        
        # set data for choices
        #self.params["choices"] = map(lambda x: x["label"], data)
        
    def create(self, meta_widget):
        self._setParams(meta_widget)

        self.tree = wx.TreeCtrl(**self.params)

        try:
            data = meta_widget.getDataProvider().getData()

            root = self.tree.AddRoot(data[0]["label"])
            self._AddTreeNodes(root, data[1])
            self.tree.Expand(root)
        except: pass

        FontProperty().set(meta_widget, self.tree)

        return self.tree
    
    def _AddTreeNodes(self, parent_item, items):
        previous_item = None
        for item in items:
            if type(item) == type({}):
                previous_item = self.tree.AppendItem(parent_item, item['label'])
            elif type(item) == type([]):
                previous_item = self.tree.AppendItem(parent_item, item[0]['label'])
                self._AddTreeNodes(previous_item, item[1])
